package com.fenrirtec.aepp.common.service.impl;

import java.sql.Connection;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fenrirtec.aepp.common.dao.AttachmentDao;
import com.fenrirtec.aepp.common.dao.TenderDao;
import com.fenrirtec.aepp.common.dao.impl.AttachmentDao_JDBCImpl;
import com.fenrirtec.aepp.common.dao.impl.TenderDao_JDBCImpl;
import com.fenrirtec.aepp.common.dto.AttachmentDto;
import com.fenrirtec.aepp.common.model.Attachment;
import com.fenrirtec.aepp.common.model.TenderDetail;
import com.fenrirtec.aepp.common.service.TenderDocService;
import com.fenrirtec.core.database.DatabaseSessionManager;
import com.fenrirtec.core.exception.DatabaseException;
import com.fenrirtec.core.exception.UnexpectedException;
import com.fenrirtec.core.utils.BeanCopierUtils;

public class TenderDocServiceImpl implements TenderDocService {
	
	private static final Logger logger = LoggerFactory.getLogger(TenderDocServiceImpl.class);

    @Override
    public AttachmentDto find(Integer tenderId) {
        if (logger.isInfoEnabled()) {
            logger.info("[TenderDocServiceImpl#find] start.");
        }
        
        DatabaseSessionManager sessionManager = DatabaseSessionManager.getInstance();
        sessionManager.open();
        Connection connection = sessionManager.getSession();
        TenderDetail tenderDetail = null;
        Attachment attachment = null;
        
        try {
            connection.setAutoCommit(false);
            TenderDao tenderDao = new TenderDao_JDBCImpl();
            tenderDetail = tenderDao.findDetail(tenderId);
            if (tenderDetail != null) {
                AttachmentDao attachmentDao = new AttachmentDao_JDBCImpl();
                attachment = attachmentDao.searchAttachment(tenderDetail.getTenderTemplate());
            }
            connection.commit();
        } catch (DatabaseException e) {
            // expected
            if (logger.isErrorEnabled()) {
                logger.error("[TenderDocServiceImpl#find] database error occurred.", e);
            }
            try {
                connection.rollback();
            } catch (SQLException e1) {
            }
            throw e;
        } catch (Exception e) {
            // unexpected
            if (logger.isErrorEnabled()) {
                logger.error("[TenderDocServiceImpl#find] unexpected error occurred.", e);
            }
            try {
                connection.rollback();
            } catch (SQLException e1) {
            }
            throw new UnexpectedException("unexpected error.", e);
        } finally {
            if (logger.isInfoEnabled()) {
                logger.info("[TenderDocServiceImpl#find] finish.");
            }
            sessionManager.close();
        }
        
        AttachmentDto attachmentDto = null;
        if (attachment != null) {
            attachmentDto = new AttachmentDto();
            BeanCopierUtils.copyProperties(attachment, attachmentDto);
        }
        
        return attachmentDto;
    }

    @Override
    public Integer upload(Integer tenderId, AttachmentDto attachmentDto) {
        if (logger.isInfoEnabled()) {
            logger.info("[TenderDocServiceImpl#upload] start.");
        }
        
        DatabaseSessionManager sessionManager = DatabaseSessionManager.getInstance();
        sessionManager.open();
        Connection connection = sessionManager.getSession();
        Integer attachmentId = null;
        
        try {
            connection.setAutoCommit(false);
            AttachmentDao attachmentDao = new AttachmentDao_JDBCImpl();
            attachmentId = attachmentDao.saveAttachment(attachmentDto.getFileType(), attachmentDto.getPath(), attachmentDto.getComment(), attachmentDto.getUploadUser());
            
            if (attachmentId != null && attachmentId > 0) {
                TenderDao tenderDao = new TenderDao_JDBCImpl();
                Boolean result = tenderDao.deleteTemplate(tenderId);
                if (!result) {
                    connection.rollback();
                    return null;
                }
                result = tenderDao.bindTemplate(tenderId, attachmentId);
                if (!result) {
                    connection.rollback();
                    return null;
                }
            }
            
            connection.commit();
        } catch (DatabaseException e) {
            // expected
            if (logger.isErrorEnabled()) {
                logger.error("[TenderDocServiceImpl#upload] database error occurred.", e);
            }
            try {
                connection.rollback();
            } catch (SQLException e1) {
            }
            throw e;
        } catch (Exception e) {
            // unexpected
            if (logger.isErrorEnabled()) {
                logger.error("[TenderDocServiceImpl#upload] unexpected error occurred.", e);
            }
            try {
                connection.rollback();
            } catch (SQLException e1) {
            }
            throw new UnexpectedException("unexpected error.", e);
        } finally {
            if (logger.isInfoEnabled()) {
                logger.info("[TenderDocServiceImpl#upload] finish.");
            }
            sessionManager.close();
        }
        
        return attachmentId;
    }

}
